﻿using DevExpress.XtraWaitForm;
using MDK.Common;
using MDK.Device;
using MDK.Device.Devices;
using MDK.Model.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace MDK.Winform
{
    public partial class frmWait : BaseForm
    {
        public frmWait()
        {
            InitializeComponent();
        }
        public frmWait(T_Handover handOver) : this()
        {
            _handOver = handOver;
            InitEvent();
        }
       
        private T_Handover _handOver;
        private void InitEvent()
        {
            EventHelper.Add("HandoverStateChanged", HandoverStateChanged);
            EventHelper.Add("EndHandover", EndHandover);
        }

        private void EndHandover(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 交接单状态改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandoverStateChanged(object sender, EventArgs e)
        {
            var args = sender as Dictionary<string, object>;
            var arg = args["arg"] as HandoverStateChangedArgs;
            if (arg.Code == FlowMesssages.AtmIdentifyTubeFail || arg.Code == FlowMesssages.AtmIdentifyTubeSuccess)
            {
               
                frmIdentification frm = new frmIdentification(arg.Types);
                if (frm.ShowDialog() == DialogResult.Cancel)
                {
                    arg.Types = frm._Types;
                    args["arg"] = arg;
                }

            }
            else
            {
                lbMeessage.Invoke(new MethodInvoker(() =>
                {
                    if (lbMeessage.IsHandleCreated)
                    {
                        lbMeessage.Text = arg.Message;
                    }
                }));
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmWait_FormClosing(object sender, FormClosingEventArgs e)
        {
            EndHandover();
            EventHelper.Remove("HandoverStateChanged");
            EventHelper.Remove("EndHandover");
        }

        private void EndHandover()
        {
            //调用API 关门结束交接
            string url = WebApiProxyHelper.StructureUrl(App.systemSetting["FrontWebApiProxyAddress"], App.systemSetting["FrontWebApiProxyPort"], "Handover/EndHandover");
            WebApiProxyHelper.Post<bool>(url, true);

            _handOver.State = "交接完成";
            WebAPIHelper.Post<T_Handover>("HandOver/Modify", _handOver);
        }

      
    }
}